package ma.fsm.arda.service;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

import com.sun.jersey.spi.resource.Singleton;

import ma.fsm.arda.command.AutoCommand;
import ma.fsm.arda.command.Command;
import ma.fsm.arda.command.strategy.Explorer;

@Path("/")
@Singleton
public class ArdaService {

	private Command command;
	private AutoCommand auto;

	public ArdaService() {

		// command = new Command("COM30");
	}

	@GET
	@Path("teststart")
	public String teststart() {
		auto = new AutoCommand();
		auto.setStrategy(new Explorer());
		Thread t = new Thread(auto);
		t.start();
		System.out.println("TEST TEST called");

		return "complete";
	}

	@GET
	@Path("teststop")
	public String teststop() {
		auto.stop();
		return "complete";
	}

	@GET
	@Path("init/{port}")
	public String init(@PathParam("port") String port) {
		if (command == null) {
			System.out.println(port);
			command = new Command(port);
			auto = new AutoCommand();

		}
		return command.getState();

	}

	@GET
	@Path("test")
	public String test() {

		System.out.println("TEST TEST called");

		return "complete";
	}

	@GET
	@Path("stop")
	public String stop() {
		String r = null;
		try {
			command.stop();
			r = command.getState();
		} catch (Exception e) {
			r = e.getMessage();
		}

		return r;
	}

	@GET
	@Path("forward")
	public String forward() {
		String r = null;
		try {
			command.goForward();
			r = command.getState();
		} catch (Exception e) {
			r = e.getMessage();
		}

		return r;
	}

	@GET
	@Path("backward")
	public String backward() {

		String r = null;
		try {
			command.goBackward();
			r = command.getState();
		} catch (Exception e) {
			r = e.getMessage();
		}

		return r;
	}

	@GET
	@Path("left")
	public String left() {

		String r = null;
		try {
			command.goLeft();
			r = command.getState();
		} catch (Exception e) {
			r = e.getMessage();
		}

		return r;
	}

	@GET
	@Path("right")
	public String right() {

		String r = null;
		try {
			command.goRight();
			r = command.getState();
		} catch (Exception e) {
			r = e.getMessage();
		}

		return r;
	}

	@GET
	@Path("explorer")
	public String explorer() {

		String r = null;
		try {
			auto.setStrategy(new Explorer(command));
			Thread t = new Thread(auto);
			t.start();
			System.out.println("started---------------");
			r = command.getState();
		} catch (Exception e) {
			r = e.getMessage();
		}

		return r;
	}

	@GET
	@Path("autostop")
	public String autoStop() {

		String r = null;
		try {
			auto.stop();

			r = command.getState();
		} catch (Exception e) {
			r = e.getMessage();
		}

		return r;
	}

}
